import {
  getInterfaceInfoByIdUsingGet,
  invokeInterfaceInfoUsingPost,
} from '@/services/openAPI-backend/interfaceInfoController';
import { useParams } from '@@/exports';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Descriptions,
  Divider,
  Flex,
  Form,
  Input,
  Row,
  Col,
  message,
  notification,
  Upload,
  UploadProps,
  Badge,
  Popover, List, Image
} from 'antd';
import React, { useEffect, useState,useRef } from 'react';
import CryptoJS from "crypto-js";
import { Link, history } from '@umijs/max';
import {getLoginUserUsingGet} from "@/services/openAPI-backend/userController";
import {uploadUsingPost} from "@/services/openAPI-backend/upLoadController";
import {PlusOutlined, UploadOutlined} from "@ant-design/icons";
import type { DescriptionsProps } from 'antd';
import {keyframes} from "antd-style";
/**
 * 每个用户都能看到的接口表格
 * @param param0
 * @returns
 */

const Index: React.FC = () => {
  const [requestData, setRequestData] = useState<{ requestParams?: string } | null>(null);
  const [loading, setLoading] = useState(false);
  const [data,setData ] = useState<API.InterfaceInfo>();
  const [invokeRes, setInvokeRes] = useState<any>();
  const [invokeLoading, setInvokeLoading] = useState(false);
  const params = useParams();
  const [loginUser, setLoginUser]=useState<API.User>();
  const [imageUrl, setImageUrl] = useState<string>();
  const formRef = useRef(null);
  const numberElement = document.getElementById("sse");

  let buffer = ''; // 创建缓冲区存储接收到的数据
  const fadeAndScaleIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
      `;
  const getSSE = async () => {
    const numberElement = document.getElementById("sse");
    numberElement.innerHTML = '';
    const source = new EventSource('http://121.40.232.157:7529/api/ssSent?interfaceInfoId=12');

    source.onmessage = (event) => {
      buffer += event.data; // 在缓冲区累积数据

      // 使用requestAnimationFrame进行批量更新
      requestAnimationFrame(() => {
        numberElement.innerHTML += buffer; // 使用innerText代替innerHTML以提高性能
        buffer = ''; // 清空缓冲区，准备下一轮数据收集
        // 打印当前显示的文本
      });
    };

  }


  const getLoginUser = async () => {
    try {
      const res = await getLoginUserUsingGet();
      sessionStorage.setItem('loginUser', JSON.stringify(res.data))
      const imminentUser = JSON.parse(sessionStorage.getItem('loginUser'))
      setLoginUser(imminentUser);
    }catch (e){
      history.push('/user/login')
    }
  }
  const onFinish = async (values: any) => {
    if(params.id!=='12') {
      const hide = message.loading('operating');
      if (!params.id) {
        message.error('接口不存在');
        return;
      }
      setInvokeLoading(true);
      try {

        const headers = {
          'AccessKey': loginUser.accessKey,
          'sign': seckeyMd5,
        };
        const querystring = new URLSearchParams(headers).toString()
        // 登录
        let randomIntegerInRange = Math.floor(Math.random() * (100))
        let currentTimeInSeconds = Math.floor(Date.now() / 1000);
        const finalString = currentTimeInSeconds + '.' + loginUser.secretKey
        const seckeyMd5 = CryptoJS.MD5(finalString).toString();
        const res = await invokeInterfaceInfoUsingPost({
          id: data.id,
          userRequestParams: values.requestParam,
          accessKey: loginUser.accessKey,
          sign: seckeyMd5,
          timestamp: currentTimeInSeconds,
          url: data.url,
        });
        if (!res.data) {
          message.error('调用失败');
          return;
        }
        setInvokeRes(res.data);
        message.success('调用成功');
        setInvokeLoading(false);
        return true;
      } catch (error) {
        hide();
        message.error('调用失败,请检查您的账户余额');
        setInvokeLoading(false);
        return false;
      }
      setInvokeLoading(false);
    }else{
      const hide = message.loading('operating');
      if (!params.id) {
        message.error('接口不存在');
        return;
      }
      getSSE();
      try {

        const headers = {
          'AccessKey': loginUser.accessKey,
          'sign': seckeyMd5,
        };
        const querystring = new URLSearchParams(headers).toString()
        // 登录
        let randomIntegerInRange = Math.floor(Math.random() * (100))
        let currentTimeInSeconds = Math.floor(Date.now() / 1000);
        const finalString = currentTimeInSeconds+'.'+loginUser.secretKey
        const seckeyMd5 = CryptoJS.MD5(finalString).toString();
        const res = await invokeInterfaceInfoUsingPost({
          id:data.id,
          userRequestParams:values.requestParam,
          accessKey: loginUser.accessKey,
          sign: seckeyMd5,
          timestamp:currentTimeInSeconds,
          url:data.url,
        });

        if (!res.data) {
          message.success('调用成功');
          return;
        }
        message.error('调用失败');

        setInvokeLoading(false);
        return true;
      } catch (error) {
        hide();
        message.error('调用失败,请检查您的账户余额');
        setInvokeLoading(false);
        return false;
      }
      setInvokeLoading(false);
    };
    const loadData = async () => {
      /*if (!params.id) {
        message.error('参数不存在');
        return;
      }*/
      setLoading(true);
      try {
        const res = await getInterfaceInfoByIdUsingGet({
          id: Number(params.id),
        });
        setData(res.data);
      } catch (error) {
        message.error('请求失败，');
      }

      setLoading(false);
    }
  };
  const loadData = async () => {
    /*if (!params.id) {
      message.error('参数不存在');
      return;
    }*/
    setLoading(true);
    try {
      const res = await getInterfaceInfoByIdUsingGet({
        id: Number(params.id),
      });
      let date = new Date(res.data?.updateTime)
      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2);
      let day = ("0" + date.getDate()).slice(-2);
      res.data.updateTime = year + '-' + month + '-' + day;
      let date1 = new Date(res.data?.createTime)
      let year1 = date1.getFullYear();
      let month1 = ("0" + (date1.getMonth() + 1)).slice(-2);
      let day1 = ("0" + date1.getDate()).slice(-2);
      res.data.createTime = year1 + '-' + month1 + '-' + day1;
      setData(res.data);
    } catch (error) {
      message.error('请求失败，');
    }

    setLoading(false);
  };
  function tryLegacyCopy(url) {
    // 创建一个隐藏的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = url;
    textarea.style.position = 'fixed'; // 防止影响页面布局
    textarea.style.top = 0;
    textarea.style.left = 0;
    textarea.style.width = '1px';
    textarea.style.height = '1px';
    textarea.style.padding = 0;
    textarea.style.border = 'none';
    textarea.style.outline = 'none';
    textarea.style.boxShadow = 'none';
    textarea.style.background = 'transparent';

    document.body.appendChild(textarea);
    textarea.select();

    // 尝试复制
    const copied = document.execCommand('copy');

    // 清理
    document.body.removeChild(textarea);

    if (copied) {
      message.success('图片url已复制到剪切板');
    } else {
      console.error('Failed to copy URL to clipboard with the legacy method');
      // 可以进一步处理错误情况
    }
  }

  const copyUrl = (url: string) => {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
          .writeText(url)
          .then(() => {
            message.success('图片url已复制到剪切板');
          })
          .catch((error) => {
            console.error('Error copying URL to clipboard:', error);
            // 处理错误，例如显示警告信息
          });
    }else{
      tryLegacyCopy(url);
    }
  };
  const customRequest = async (image) => {
    const form = new FormData();
    form.append('image', image.file);

    // form 对象 就是我们上传接口需要的参数
    // 调用api接口进行请求 , uploadFile 是走我们封装的 请求的 , 请求头 token 都包含
    try {
      const res = await uploadUsingPost(form);
      setImageUrl(res.data);
      copyUrl(res.data);
      notification.info({
        message: '系统提示',
        description: '图片上传成功,url已复制到您的剪切板中！',
        placement: 'topRight',
        duration: 2,
      });
    } catch (e) {
      notification.info({
        message: '系统提示',
        description: '图片上传失败',
        placement: 'topRight',
        duration: 2,
      });
    }
    // 拿到调取接口返回的数据
  };
  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };
  const uploadProps = {
    name: 'image', //取值必须和接口参数中的文件参数名相同： MultipartFile file
    multiple: true,
    showUploadList: false,
    customRequest: customRequest,
  };
  const uploadButton = (
      <button style={{ border:0, background: 'none', marginTop: 0,width: 150,height: 150 }} size={'large'} type="button">
        <PlusOutlined/>
        <div style={{ marginTop: 0 }}>Upload</div>
      </button>
  );
  useEffect(() => {
    loadData();
    getLoginUser();
  }, []);
  useEffect(() => {
    formRef.current?.setFieldsValue({
      requestParam: data?.requestParams,
    });
  }, [data]);
  const items: DescriptionsProps['items'] = [
    {
      key: '1',
      label: '接口ID',
      children: data?.id,
      style: { width: '8%' },
      contentStyle: { width: '20%' },
    },
    {
      key: '2',
      label: '接口名称',
      children: data?.name,
      style: { width: '8%' },
      contentStyle: { width: '27%' },
    },
    {
      key: '3',
      label: 'Status',
      style: { width: '8%' },
      contentStyle: { width: '27%' },
      children: data?.status === 1 ?<Badge status="processing" text="Running" />:<Badge status="error" text="Error" />,
    },
    {
      key: '4',
      label: '创建时间',
      children: data?.createTime,
    },
    {
      key: '5',
      label: '更新时间',
      children: data?.updateTime,
    },
    {
      key: '6',
      label: '请求方法',
      children: data?.method,
    },

    {
      key: '8',
      label: '服务费用',
      children: data?.aiSign == "1"?"token计费":data?.pointsCost+"积分/每次",
    },
    {
      key: '9',
      label: '请求url',
      children: data?.url,
    },
    {
      key: '10',
      label: '请求参数',
      children: data?.requestParams,
    },
    {
      key: '7',
      label: '描述',
      children: data?.description,
      span: 3,
    },
    {
      key: '11',
      label: '请求头',
      children: (
          <div style={{whiteSpace: 'pre-wrap'}}>{data?.requestHeader}</div>
      ),
    },
  ];
  const itemsParam: DescriptionsProps['items'] = [
    {
      key: '1',
      label: 'Accesskey',
      children: <div style={{fontSize: "16px"}}>您的Accesskey（详见秘钥管理）</div>,
    },
    {
      key: '2',
      label: 'Sign',
      children: <div style={{fontSize: "16px"}}>您的Secretkey与字符.和当前时间戳（详见时间戳标头）拼接后MD5加密后的值（Secretkey详见秘钥管理）</div>,
    },
    {
      key: '3',
      label: 'Timestamp',

      children: <div style={{fontSize: "16px"}}>您请求当前的时间戳（平台用以防止恶意调用）：取到当前毫秒后除以1000。示例:2024/4/25 11:31（北京标准时间），取 1714015894</div>,
    },
    {
      key: '4',
      label: 'InterfaceID',

      children: <div style={{fontSize: "16px"}}>您请求的接口ID（详见上方表格文档）</div>,
    },
  ];
  const itemsRequest: DescriptionsProps['items'] = [
    {
      key: '1',
      label: 'id',
      children: <div style={{fontSize: "16px"}}>您请求的接口ID</div>,
      span: 20 ,
    },
    {
      key: '2',
      label: 'userRequestParams',
      children: <List style={{overflow: 'auto', height: data?.remarks.length == null ? 0: data?.remarks.length  > 150   ? 150 : "100%", width: '100%'}}>{data?.remarks}</List>,
    },
  ];

  return (
      <PageContainer title="查看接口文档" style={{animation: `${fadeAndScaleIn} 1s ease-in-out`}}>
        <Card>
          <Descriptions title="接口文档" bordered items={items} />
        </Card>
        <Card title={<p style={{ marginTop: 20, fontSize: '24px' }}>接口请求</p>}>
          <Descriptions title={<h2>Header：</h2>} labelStyle={{fontSize:"16px",fontWeight:"bold"}}  contentStyle={{fontSize: "18px"}} bordered layout="vertical" column={2} items={itemsParam} />
          <br />

          <br />
          <Descriptions bordered layout={'horizontal'} title={<h2>
            接口参数说明：
          </h2>} labelStyle={{fontSize:"18px",fontWeight:"bold",width:"18%"}}  contentStyle={{fontSize: "18px",whiteSpace: 'pre-wrap' }}  items={itemsRequest} />
          <br />
          <h2>返回参数：</h2>
          <a style={{ fontSize: '20px', color: 'black', whiteSpace: 'pre-wrap' }}>
            {'{\n' +
                'code：' +
                '状态码' +
                ',\n' +
                'data：' +
                '返回数据' +
                ',\n' +
                'message：' +
                '提示信息' +
                ',\n' +
                '}'}
          </a>
        </Card>
        <Card title={<p style={{ marginTop: 20, fontSize: '24px' }}>接口测试</p>}>
          <Form name="basic" layout={'vertical'} onFinish={onFinish} ref={formRef}>
            {data?.id === "6" && (
                <Row>
                  <Col>
                    <Upload
                        {...uploadProps}
                        name="avatar"
                        listType="text"
                        className="avatar-uploader"
                        onChange={handleChange}
                        style={{
                          marginLeft: 0,
                          width: '400px',
                          height: '400px',
                          border: 'none',
                        }}
                    >
                      {imageUrl ? (
                          <File></File>
                      ) : (
                          uploadButton
                      )}
                    </Upload>
                  </Col>
                  <Col>
                    {' '}
                    {data?.id === 6  &&
                        (imageUrl ? (
                            <Popover content={imageUrl} title="图片Url">
                              <Button
                                  style={{ marginLeft: '90px' }}
                                  onClick={() => {
                                    copyUrl(imageUrl);
                                  }}
                                  type="primary"
                              >
                                点击复制
                              </Button>
                            </Popover>
                        ) : (
                            <div></div>
                        ))}
                  </Col>
                </Row>
            )}
            {data?.id === "19" && (
              <>
              <Upload
                {...uploadProps}
                name="avatar"
                listType="picture"
                className="avatar-uploader"
                onChange={handleChange}
                style={{
                  marginLeft: 0,
                  width: '400px',
                  height: '400px',
                  border: 'none',
                }}
              >
                  <Button icon={<UploadOutlined />}>Upload</Button>

              </Upload>
            {imageUrl ? (
              <Popover content={imageUrl} title="文件Url">
            <Button
              style={{ marginLeft: '90px' }}
              onClick={() => {
                copyUrl({imageUrl});
              }}
              type="primary"
            >
              点击复制文件URL
            </Button>
          </Popover>
          ) : (
          <div></div>
          )}
              </>
            )}
            <Form.Item
                label={<p style={{ fontWeight: 'bold', fontSize: '22px' }}>请求参数</p>}
                name="requestParam"
            >
              <Input.TextArea
                  autoSize={true}
                  style={{ height: '6vw', display: 'inline-block' }}
                  showCount="true"
                  size="large"
              />
            </Form.Item>
            <Form.Item>
              <Flex justify={'flex-start'}>
                <Button type="primary" htmlType="submit">
                  测试
                </Button>
              </Flex>

            </Form.Item>
          </Form>
          <Divider />
        </Card>
        <Card
          style={{whiteSpace: 'pre-wrap'}}
          title={<p style={{fontWeight: 'bold', fontSize: '22px', marginTop: 20}}>调用结果</p>}
          loading={invokeLoading}
        >

          <div style={{whiteSpace: 'pre-line'}}>{invokeRes}</div>
          {params.id === '14' && invokeRes && (<audio controls={true}>
            <source src={invokeRes} type="audio/mpeg"/>
          </audio>)}
          {params.id === '23' && invokeRes && (<Image src={invokeRes}></Image>)}
          {params.id === '12' && (<h2 style={{
            whiteSpace: 'pre-wrap',
          }}>Receive: <pre style={{
            whiteSpace: 'pre-wrap',
            fontSize: '16px',
          }} id="sse"></pre></h2>)}
        </Card>
      </PageContainer>
  );
};

export default Index;
